const taskModel = require('../models/taskModel');

class TaskController {
  /**
   * 获取任务列表
   * @param {*} ctx 
   */
  async getTaskList(ctx) {
    try {
      const tasks = await taskModel.getTaskList(ctx);
      ctx.set('Cache-Control', 'no-cache')
      ctx.body = { code: 200, data: tasks, message: '获取成功' };
    } catch (error) {
      ctx.body = { code: 500, message: '获取失败', error };
    }
  }

  /**
   * 添加
   * @param {*} ctx 
   */
  async addTask(ctx) {
    try {
      const { title, datetime, author, authorId, status } = ctx.request.body;
      const id = await taskModel.addTask({ title, datetime, author, authorId, status });
      ctx.body = { code: 200, data: { id }, message: '添加成功' };
    } catch (error) {
      ctx.body = { code: 500, message: '添加失败', error };
    }
  }

  /**
   * 更新
   * @param {*} ctx 
   */
  async updateTask(ctx) {
    try {
      const id = ctx.params.id;
      const { title, datetime, author, authorId, status } = ctx.request.body;
      const affectedRows = await taskModel.updateTask(id, { title, datetime, author, authorId, status });

      if (affectedRows > 0) {
        ctx.body = { code: 200, message: '更新成功' };
      } else {
        ctx.body = { code: 404, message: '任务不存在' };
      }
    } catch (error) {
      ctx.body = { code: 500, message: '更新失败', error };
    }
  }

  /**
   * 删除
   * @param {*} ctx 
   */
  async deleteTask(ctx) {
    try {
      const id = ctx.params.id;
      const affectedRows = await taskModel.deleteTask(id);

      if (affectedRows > 0) {
        ctx.body = { code: 200, message: '删除成功' };
      } else {
        ctx.body = { code: 404, message: '任务不存在' };
      }
    } catch (error) {
      ctx.body = { code: 500, message: '删除失败', error };
    }
  }
}

module.exports = new TaskController();